import os

from alipay import AliPay
from django import http
from django.conf import settings
from django.shortcuts import render
from django.views import View

from orders.models import OrderInfo
from payment.models import Payment
from users.views import LoginRequiedView
from utils.response_code import RET


class PaymentView(LoginRequiedView):
    def get(self, request, order_id):
        # 获取支付宝支付链接
        # 1, 初始化数据
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except Exception as e:
            return http.JsonResponse({'code': RET.PARAMERR, 'errmsg': '订单编号有误'})

        # 2, 处理业务逻辑
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({'code': RET.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})

        # 3, 返回响应
        pass


class PaymentStatusView(View):
    # 不需要登录
    def get(self, request):
        # 接收支付宝回调, 用户的重定向
        # 1, 初始化数据
        data = request.GET.dict()  # 后面需要用到参数字典, 需要dict, 需要把query_dict  -> dict
        sign = data.pop('sign')
        # data 中剩下 除去sign 后的所有参数.  剩下的数据用来用来做签名运算
        # sign不能参与签名运算,
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data, sign)

        # 2, 处理业务逻辑
        if success:
            # 保存数据
            Payment.objects.create(
                order_id=data.get('out_trade_no'),
                trade_id=data.get('trade_no')
            )
            OrderInfo.objects.filter(order_id=data.get('out_trade_no')).update(status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])
            # 订单状态应该是:  UNSEND
            # 现在假设已经发货和收货了, 订单状态由  UNSEND  ->  UNRECEIVED  ->  UNCOMMENT
        else:
            # 数据有误
            return http.HttpResponseForbidden('信息有误')
            pass

        # 3, 返回响应
        context = {
            'order_id': data.get('out_trade_no')
        }
        return render(request, 'pay_success.html', context=context)
        pass
